"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 系统视图权限测试
Case Name   : 普通用户查询系统表GS_CLIENT_GLOBAL_KEYS为空
Create At   : 2023/06/07
@zou_jialiang0501162244
Description :
    1、配置$GAUSSHOME/etc/localkms路径
    2、连接全密态数据库，创建普通用户，创建cmk、cek，查询GS_CLIENT_GLOBAL_KEYS
    3、普通用户查询系统表GS_CLIENT_GLOBAL_KEYS
    4、清理环境
Expect      :
    1、配置成功
    2、创建成功，查询1条数据
    3、查询为空
    4、成功
History     :
"""

import os
import unittest

from yat.test import Node
from yat.test import macro
from testcase.utils.Constant import Constant
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Logger import Logger


class SecurityDesign(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.cons = Constant()
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.pri_node = Node('PrimaryDbUser')
        self.user = 'u_privilege_0021'
        self.cmk = 'cmk_privilege_0021'
        self.cek = 'cek_privilege_0021'
        self.key_path = 'keypath_privilege_0021'
        self.localkms = os.path.join(macro.DB_INSTANCE_PATH, '..', 'app',
                                     'etc', 'localkms')

    def test_security(self):
        text1 = '-----step1:配置$GAUSSHOME/etc/localkms路径;expect:成功-----'
        self.log.info(text1)
        mkdir_cmd = f'if [ ! -d "{self.localkms}" ];' \
                    f'then mkdir {self.localkms};fi'
        self.log.info(mkdir_cmd)
        res = self.pri_node.sh(mkdir_cmd).result()
        self.log.info(res)
        self.assertEqual('', res, f"执行失败:{text1}")

        text2 = '-----step2:连接全密态数据库，创建普通用户，创建cmk、cek，' \
                '查询系统表GS_CLIENT_GLOBAL_KEYS;expect:成功，1条数据-----'
        self.log.info(text2)
        sql_cmd = f'''drop user if exists {self.user} cascade;
         create user {self.user} password '{macro.COMMON_PASSWD}';
         drop client master key if exists {self.cmk};
         create client master key {self.cmk} with
         (key_store = localkms, key_path = "{self.key_path}", 
         algorithm = rsa_3072);
         drop column encryption key if exists {self.cek} cascade;
         create column encryption key {self.cek} with values
         (client_master_key = {self.cmk}, 
         algorithm = aead_aes_256_cbc_hmac_sha256);
         select * from gs_client_global_keys;'''
        sql_result = self.pri_sh.execut_db_sql(sql_cmd, sql_type='-C')
        self.log.info(sql_result)
        self.assertIn(self.cons.CREATE_ROLE_SUCCESS_MSG, sql_result,
                      f"创建用户失败:{text2}")
        self.assertTrue(self.cons.create_cmk_success in sql_result and
                        self.cons.create_cek_success in sql_result and
                        '1 row' in sql_result, f"执行失败:{text2}")

        text3 = '-----step3:普通用户查询系统表GS_CLIENT_GLOBAL_KEYS;expect:空-----'
        self.log.info(text3)
        select_result = self.pri_sh.execut_db_sql(
            "select * from gs_client_global_keys;",
            sql_type=f'-C -U {self.user} -W{macro.COMMON_PASSWD}')
        self.log.info(select_result)
        self.assertIn('0 rows', select_result, f"执行失败:{text3}")

    def tearDown(self):
        text4 = '-----step4:清理环境;expect:成功-----'
        self.log.info(text4)
        sql_cmd = f'''drop user if exists {self.user} cascade;
        drop column encryption key {self.cek} cascade;
        drop client master key {self.cmk} cascade;'''
        msg = self.pri_sh.execut_db_sql(sql_cmd, sql_type='-C')
        self.log.info(msg)
        del_cmd = f'rm -rf {self.localkms}'
        self.log.info(del_cmd)
        del_res = self.pri_node.sh(del_cmd).result()
        self.log.info(del_res)
        self.assertIn(self.cons.DROP_ROLE_SUCCESS_MSG, msg, f"删用户失败:{text4}")
        self.assertIn(self.cons.drop_cek_success, msg, f"执行失败:{text4}")
        self.assertIn(self.cons.drop_cmk_success, msg, f"执行失败:{text4}")
        self.assertEqual('', del_res, f"执行失败:{text4}")
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
